package com.etc.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.rowset.CachedRowSet;

import com.etc.dao.IEmployeesDao;
import com.etc.dao.lLeaveapprovallDao;
import com.etc.entity.Employees;
import com.etc.entity.LeaveApproval;
import com.etc.entity.Records;
import com.etc.util.DBUtil;

public class LeaveapprovallDaoImpl implements lLeaveapprovallDao {
	private IEmployeesDao dao = new EmployeesDaoImpl();
	/**
	 * 添加请假条
	 * leave:请假条对象
	 * return:boolean值
	 */
	@Override
	public boolean addLeave(LeaveApproval leave) {
		return 	DBUtil.executeUpdate("insert into leaveapproval values(null,?,?,?,?,0)",leave.getEmp().getEmpId(),leave.getLeaveReasons(),leave.getLeaveTime(),leave.getBackTime());
		
	}

	/**
	 * 查询部门内的所有请假条
	 * deptId:部门编号
	 * return:请假条集合
	 */
	@Override
	public List<LeaveApproval> queryLeaveByDeptId(int deptId) {
		List<LeaveApproval> list = new ArrayList<LeaveApproval>();
		String sql = "select a.* from leaveapproval a INNER JOIN (select empId from employees where deptId = ?) b on a.empId = b.empId order by a.result,a.leaveTime desc";
		CachedRowSet crs = DBUtil.executeQuery(sql, deptId);
		LeaveApproval leave = null;
		try {
			while(crs.next()) {
				int approvalId = crs.getInt(1);
				int empId = crs.getInt(2);
				String leaveReasons = crs.getString(3);
				String leaveTime = crs.getString(4);
				String backTime = crs.getString(5);
				int result = crs.getInt(6);
				Employees emp = dao.queryById(empId);
				leave = new LeaveApproval(approvalId, leaveReasons, leaveTime.substring(0,leaveTime.length()-2), backTime.substring(0,backTime.length()-2), result, emp);
				list.add(leave);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public boolean updateLeaveResult(int approvalId,int result) {
		return DBUtil.executeUpdate("update leaveapproval set result = ? where approvalId = ?", result,approvalId);
	}
	
	/**
	 * 查询员工自己的提交的请假申请
	 * id:员工id
	 * return:记录对象
	 */
	@Override
	public List<LeaveApproval> queryMyLeaveById(int empId) {
		String sql = "select * from leaveapproval where empId = ? order by leaveTime desc";
		CachedRowSet crs = DBUtil.executeQuery(sql, empId);
		List<LeaveApproval> list = new ArrayList<>();
		LeaveApproval leave = null;
		try {
			while(crs.next()) {
				int approvalId = crs.getInt(1);
				String leaveReasons = crs.getString(3);
				String leaveTime = crs.getString(4);
				String backTime = crs.getString(5);
				int result = crs.getInt(6);
				Employees emp = dao.queryById(empId);
				leave = new LeaveApproval(approvalId, leaveReasons, leaveTime, backTime, result, emp);
				list.add(leave);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

}
